/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ses;

import Entity.AccountsType;
import ses.exceptions.NonexistentEntityException;
import ses.exceptions.RollbackFailureException;
import java.io.Serializable;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import Entity.Accounts;
import java.util.ArrayList;
import java.util.List;
import javax.transaction.UserTransaction;

/**
 *
 * @author Huu Vinh
 */
public class AccountsTypeJpaController implements Serializable {

    public AccountsTypeJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(AccountsType accountsType) throws RollbackFailureException, Exception {
        if (accountsType.getAccountsList() == null) {
            accountsType.setAccountsList(new ArrayList<Accounts>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            List<Accounts> attachedAccountsList = new ArrayList<Accounts>();
            for (Accounts accountsListAccountsToAttach : accountsType.getAccountsList()) {
                accountsListAccountsToAttach = em.getReference(accountsListAccountsToAttach.getClass(), accountsListAccountsToAttach.getAccId());
                attachedAccountsList.add(accountsListAccountsToAttach);
            }
            accountsType.setAccountsList(attachedAccountsList);
            em.persist(accountsType);
            for (Accounts accountsListAccounts : accountsType.getAccountsList()) {
                AccountsType oldTypeIdOfAccountsListAccounts = accountsListAccounts.getTypeId();
                accountsListAccounts.setTypeId(accountsType);
                accountsListAccounts = em.merge(accountsListAccounts);
                if (oldTypeIdOfAccountsListAccounts != null) {
                    oldTypeIdOfAccountsListAccounts.getAccountsList().remove(accountsListAccounts);
                    oldTypeIdOfAccountsListAccounts = em.merge(oldTypeIdOfAccountsListAccounts);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(AccountsType accountsType) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            AccountsType persistentAccountsType = em.find(AccountsType.class, accountsType.getTypeId());
            List<Accounts> accountsListOld = persistentAccountsType.getAccountsList();
            List<Accounts> accountsListNew = accountsType.getAccountsList();
            List<Accounts> attachedAccountsListNew = new ArrayList<Accounts>();
            for (Accounts accountsListNewAccountsToAttach : accountsListNew) {
                accountsListNewAccountsToAttach = em.getReference(accountsListNewAccountsToAttach.getClass(), accountsListNewAccountsToAttach.getAccId());
                attachedAccountsListNew.add(accountsListNewAccountsToAttach);
            }
            accountsListNew = attachedAccountsListNew;
            accountsType.setAccountsList(accountsListNew);
            accountsType = em.merge(accountsType);
            for (Accounts accountsListOldAccounts : accountsListOld) {
                if (!accountsListNew.contains(accountsListOldAccounts)) {
                    accountsListOldAccounts.setTypeId(null);
                    accountsListOldAccounts = em.merge(accountsListOldAccounts);
                }
            }
            for (Accounts accountsListNewAccounts : accountsListNew) {
                if (!accountsListOld.contains(accountsListNewAccounts)) {
                    AccountsType oldTypeIdOfAccountsListNewAccounts = accountsListNewAccounts.getTypeId();
                    accountsListNewAccounts.setTypeId(accountsType);
                    accountsListNewAccounts = em.merge(accountsListNewAccounts);
                    if (oldTypeIdOfAccountsListNewAccounts != null && !oldTypeIdOfAccountsListNewAccounts.equals(accountsType)) {
                        oldTypeIdOfAccountsListNewAccounts.getAccountsList().remove(accountsListNewAccounts);
                        oldTypeIdOfAccountsListNewAccounts = em.merge(oldTypeIdOfAccountsListNewAccounts);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = accountsType.getTypeId();
                if (findAccountsType(id) == null) {
                    throw new NonexistentEntityException("The accountsType with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            AccountsType accountsType;
            try {
                accountsType = em.getReference(AccountsType.class, id);
                accountsType.getTypeId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The accountsType with id " + id + " no longer exists.", enfe);
            }
            List<Accounts> accountsList = accountsType.getAccountsList();
            for (Accounts accountsListAccounts : accountsList) {
                accountsListAccounts.setTypeId(null);
                accountsListAccounts = em.merge(accountsListAccounts);
            }
            em.remove(accountsType);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<AccountsType> findAccountsTypeEntities() {
        return findAccountsTypeEntities(true, -1, -1);
    }

    public List<AccountsType> findAccountsTypeEntities(int maxResults, int firstResult) {
        return findAccountsTypeEntities(false, maxResults, firstResult);
    }

    private List<AccountsType> findAccountsTypeEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from AccountsType as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public AccountsType findAccountsType(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(AccountsType.class, id);
        } finally {
            em.close();
        }
    }

    public int getAccountsTypeCount() {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select count(o) from AccountsType as o");
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
